package com.whenjun.task;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ifootbook.util.DateStyle;
import com.ifootbook.util.TimeUtil;
import com.whenjun.common.LoggerParent;
import com.whenjun.dto.kq.KqDoorData;
import com.whenjun.dto.kq.KqRestTimeDTO;
import com.whenjun.entity.Kq;
import com.whenjun.entity.KqConfig;
import com.whenjun.enums.KqDoorTypeEnum;
import com.whenjun.enums.KqStateEnum;
import com.whenjun.service.impl.KqAlarmServiceImpl;
import com.whenjun.service.impl.KqServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
public class TaskKq extends LoggerParent {

    @Autowired
    private KqServiceImpl kqService;

    @Autowired
    private KqAlarmServiceImpl kqAlarmService;

    // 每天 00:10 分
    @Scheduled(cron = "0 10 0 1/1 * ?")
    public void kqDataCal(){
        // 默认初始化昨天数据
        Date date = new Date();
        String yyyyMMdd = TimeUtil.formatDate(TimeUtil.getLastDate(date), DateStyle.YYYY_MM_DD);

        log.info("kqDataCal start: " + yyyyMMdd);

        try {
            kqService.initKqData(yyyyMMdd);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("initKqData error: " + e.getMessage());
        }

        // 日常打卡统计, 分为上班和下班
        // 上班
        List<KqDoorData> shangbanDatas = kqService.getByDateAndGroupCode(yyyyMMdd, KqDoorTypeEnum.shangban.getCode());
        for (KqDoorData shangbanData : shangbanDatas) {
            Integer shangbanNum = shangbanData.getCnt();
            LocalDateTime shangbanTime = shangbanData.getMin_time();

            LambdaUpdateWrapper<Kq> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Kq::getDakaShangbanNum, shangbanNum)
                    .set(Kq::getDakaShangbanTime, shangbanTime)
                    .eq(Kq::getId, shangbanData.getId());
            kqService.update(wrapper);
        }

        log.info("kqDataCal end: " + yyyyMMdd);

        // 下班
        List<KqDoorData> xiabanDatas = kqService.getByDateAndGroupCode(yyyyMMdd, KqDoorTypeEnum.xiaban.getCode());
        for (KqDoorData xiabanData : xiabanDatas) {
            Integer xiabanNum = xiabanData.getCnt();
            LocalDateTime xiabanTime = xiabanData.getMax_time();

            LambdaUpdateWrapper<Kq> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Kq::getDakaXiabanNum, xiabanNum)
                    .set(Kq::getDakaXiabanTime, xiabanTime == null ? xiabanData.getMin_time() : xiabanTime)
                    .eq(Kq::getId, xiabanData.getId());
            kqService.update(wrapper);
        }

        log.info("kqData shangxiaban end: " + yyyyMMdd);

        // 休息时间统计, 包含wc，通道等
        List<KqRestTimeDTO> restTimeDatas = kqAlarmService.getBaseMapper().selectRestSumTime(yyyyMMdd);
        for (KqRestTimeDTO restTimeData : restTimeDatas) {
            // 统计考勤总时长 = 下班 - 上班 - 休息时间（大于第6个配置的最大休息时间）


            LambdaUpdateWrapper<Kq> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Kq::getRestSumTime, restTimeData.getRestSumTime() == null ? 0 : restTimeData.getRestSumTime())
                    .eq(Kq::getId, restTimeData.getId());
            kqService.update(wrapper);
        }
        log.info("kqData rest end: " + yyyyMMdd);

        kqData(yyyyMMdd);

        // 通道时间统计

        // wc时间统计

        // 以上统计无法单次给出，只能放在事件接受中处理 一律处理为休息时间
    }

    public void kqData(String yyyyMMdd) {
        try {
            // 考勤状态，考勤总时长，加班时长
            List<Kq> kqs = kqService.getByDate(yyyyMMdd);
            for (Kq kq : kqs) {
                if (kq.getId().equals("2024-12-23_2c2d1168a974405d9fb75e4f507ce3ef")) {
                    System.out.println(kq.getId());
                }
                List<String> kqStates = new ArrayList<>();
                List<String> kqStateNames = new ArrayList<>();

                // 缺勤 当天没打卡或者下班没打卡 判断为缺勤
                if (kq.getDakaShangbanTime() == null || kq.getDakaXiabanTime() == null) {
                    // 缺勤
                    kqStates.add(KqStateEnum.queqin.getCode());
                    kqStateNames.add(KqStateEnum.queqin.getName());
                } else {
                    if (kq.getDakaShangbanTime().toLocalTime().isAfter(kq.getDepartmentGroupShangbanTime())
                            || kq.getDakaXiabanTime().toLocalTime().isBefore(kq.getDepartmentGroupXiabanTime())) {
                        // 迟到
                        if (kq.getDakaShangbanTime().toLocalTime().isAfter(kq.getDepartmentGroupShangbanTime())) {
                            kqStates.add(KqStateEnum.chidao.getCode());
                            kqStateNames.add(KqStateEnum.chidao.getName());
                        }
                        // 早退
                        if (kq.getDakaXiabanTime().toLocalTime().isBefore(kq.getDepartmentGroupXiabanTime())){
                            kqStates.add(KqStateEnum.zaotui.getCode());
                            kqStateNames.add(KqStateEnum.zaotui.getName());
                        }
                    }else {

                        // 统计考勤总时长 = 下班 - 上班 - 休息时间 - (午休？)
                        // 正常考勤时长 = 下班 - 上班 - (午休？)
                        // 加班时间 = 统计考勤总时长 - 正常考勤时长

                        // 上下班时间差 秒数
                        Integer countTime = (kq.getDepartmentGroupXiabanTime().toSecondOfDay() - kq.getDepartmentGroupShangbanTime().toSecondOfDay());

                        // 考勤总时长
                        Integer countKqTime = kq.getDakaXiabanTime().toLocalTime().toSecondOfDay() - kq.getDakaShangbanTime().toLocalTime().toSecondOfDay()
                                - ((kq.getRestSumTime() == null ? 0 : kq.getRestSumTime()));


                        // 加班时长
                        Integer jiabanTime = countKqTime - countTime;

                        if (jiabanTime > 0) {
                            kqStates.add(KqStateEnum.jiaban.getCode());
                            kqStateNames.add(KqStateEnum.jiaban.getName());
                        }

                        kq.setCountKqTime(countKqTime);
                        kq.setJiabanTime(jiabanTime);
                    }
                }
                if(kqStates.isEmpty()) {
                    kqStates.add(KqStateEnum.zhengchang.getCode());
                    kqStateNames.add(KqStateEnum.zhengchang.getName());
                }
                kq.setKqState(JSON.toJSONString(kqStates));
                kq.setKqStateName(JSON.toJSONString(kqStateNames));
                kqService.updateById(kq);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("考勤状态，考勤总时长，加班时长 error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 定义格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime shangban = LocalDateTime.parse("2024-12-29 07:37:33",formatter);
        LocalDateTime xiaban = LocalDateTime.parse("2024-12-29 17:02:50",formatter);



        System.out.println(xiaban.toLocalTime().toSecondOfDay() - shangban.toLocalTime().toSecondOfDay());
    }
}
